package org.example.demowebsrocket.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

/**
 * WebSocket握手拦截器
 *
 * @author zhaokf
 * @date 13:29 2025/8/17
 */
public class WebSocketHandshakeInterceptor implements HandshakeInterceptor {
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        request.getHeaders().forEach((key, value) -> System.out.println(key + ":" + value));
        if (request instanceof ServletServerHttpRequest servletServerHttpRequest) {
            HttpServletRequest httpRequest = servletServerHttpRequest.getServletRequest();
            String username = httpRequest.getParameter("username");
            if (username != null && !username.isEmpty()) {
                attributes.put("username", username);
                return true;
            }
        }
        return false;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
        System.out.println("握手之后");
    }
}
